package com.yunc.common.oss;

import cn.hutool.core.date.DateUtil;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.yunc.common.exception.UCException;
import com.yunc.common.properties.Pro;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * 七牛云存储
 *
 * @author congcong tao
 * @date 2018/10/13 15:31
 */
@Service
public class QiniuCloudStorageService {

    @Autowired(required = false)
    private Pro pro;

    private UploadManager uploadManager;

    private String token;

    @PostConstruct
    private void init(){
        uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        token = Auth.create(pro.getQiniuAccessKey(), pro.getQiniuSecretKey()).
                uploadToken(pro.getQiniuBucketName());
    }

    public String upload(byte[] data, String path) {
        try {
            Response res = uploadManager.put(data, path, token);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
        } catch (Exception e) {
            throw new UCException("上传文件失败，请核对七牛配置信息", e);
        }

        return pro.getQiniuDomain() + "/" + path;
    }

    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new UCException("上传文件失败", e);
        }
    }

    public String upload(byte[] data) {
        return upload(data, getPath(pro.getQiniuPrefix()));
    }

    public String upload(InputStream inputStream) {
        return upload(inputStream, getPath(pro.getQiniuPrefix()));
    }

    private String getPath(String prefix){
        //生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        String path = DateUtil.format(new Date(), "yyyyMMdd") + "/" + uuid;
        if (StringUtils.isNotBlank(prefix)) {
            path = prefix + "/" + path;
        }
        return path;
    }

    public String uploadImage(byte[] data) {
        //生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        String path = DateUtil.format(new Date(), "yyyyMMdd") + "/" + uuid + ".jpeg";
        if (StringUtils.isNotBlank(pro.getQiniuPrefix())) {
            path = pro.getQiniuPrefix() + "/" + path;
        }
        return upload(data, path);
    }
}
